# -*- coding: utf-8 -*-
# @Date：2024/7/18 15:56:27
# @Author：CJiaの青姝
# @FileName：cj_ninja
# @Editor：PyCharm2024
# @Remark：
from typing import Any, List

from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse, JsonResponse
from ninja import NinjaAPI, Schema, Field
from ninja.types import DictStrAny
from ninja.pagination import PaginationBase


class CjNinjaAPI(NinjaAPI):
    def create_response(
            self,
            request: HttpRequest,
            data: Any,
            *,
            status: int = 200,
            code: int = 200,
            msg: str = "操作成功",
            temporal_response: HttpResponse = None,
    ) -> HttpResponse:
        std_data = {
            "code": code,
            "data": data,
            "message": msg,
            "success": True
        }
        content = self.renderer.render(request, std_data, response_status=status)
        content_type = "{}; charset={}".format(
            self.renderer.media_type, self.renderer.charset
        )
        return HttpResponse(content, status=status, content_type=content_type)


class MyPagination(PaginationBase):
    class Input(Schema):
        page: int = Field(1, description="当前页数", gt=-1)
        pageSize: int = Field(10, description="每页页数", gt=0)

        class Config:
            title = "分页查询参数"

    class Output(Schema):
        items: List[Any]
        total: int

        class Config:
            title = "分页列表"

    def paginate_queryset(
            self,
            queryset: QuerySet,
            pagination: Input,
            **params: DictStrAny,
    ) -> Any:
        offset = pagination.pageSize * (pagination.page - 1)
        limit: int = pagination.pageSize
        return {
            "page": offset,
            "limit": limit,
            "items": queryset[offset: offset + limit],
            "total": self._items_count(queryset),
        }  # noqa: E203


class CjFilters(Schema):
    creator: str = Field(None, description="创建人", alias="creator")
    modifier: str = Field(None, description="修改人", alias="modifier")
    status: bool = Field(default=True, description="状态", alias="status")
